package repository

import (
	"gorm.io/gorm"
	"guliedu/model"
)

type IEduChapterRepository interface {
	// 添加章节
	Insert(chapter *model.EduChapter) error
	// 更新章节
	Update(chapter *model.EduChapter) error
	// 删除章节
	DeleteByCourseID(id string) error
	// 获取所有章节以及视频
	GetAllChapterVideo(courseID string) ([]model.EduChapter, error)
	// 获取章节
	Select(id string) (*model.EduChapter, error)
	// 删除章节
	Delete(id string) error
}

func NewIEduChapterRepository() IEduChapterRepository {
	return &EduChapterRepository{mysqlDb: db}
}

type EduChapterRepository struct {
	mysqlDb *gorm.DB
}

func (t *EduChapterRepository) Insert(chapter *model.EduChapter) error {
	return t.mysqlDb.Create(&chapter).Error
}

func (t *EduChapterRepository) Update(chapter *model.EduChapter) error {
	return t.mysqlDb.Save(&chapter).Error
}

func (t *EduChapterRepository) DeleteByCourseID(id string) error {
	return t.mysqlDb.Where("course_id = ?", id).Delete(&model.EduChapter{}).Error
}

func (t *EduChapterRepository) GetAllChapterVideo(courseID string) (chapters []model.EduChapter, err error) {
	err = t.mysqlDb.Preload("Videos").Where("course_id = ?", courseID).Find(&chapters).Error
	return
}

func (t *EduChapterRepository) Select(id string) (chapter *model.EduChapter, err error) {
	err = t.mysqlDb.Where("id = ?", id).Find(&chapter).Error
	return
}

func (t *EduChapterRepository) Delete(id string) error {
	return t.mysqlDb.Where("id = ?", id).Delete(&model.EduChapter{}).Error
}
